package com.xiao.permission_system.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//会拦截注解了@PreAuthrize注解的配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().anyRequest().authenticated();
        http.formLogin().usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login")
                .successHandler(new LoginSuccessHandler())
                .loginPage("/login")
                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll() //允许所有人可以访问登陆页面
                .antMatchers("/", "/index").permitAll()
                .antMatchers("/test/**", "/test1/**", "/favicon.ico").permitAll()
                .antMatchers("/res/**/*.{js,html}").permitAll()

                .anyRequest().access("@authService.canAcess(request,authentication)")
                .and().sessionManagement().maximumSessions(1);
        //.anyRequest().authenticated();//所有的请求需要在登陆之后才能访问

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
